import type { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'

// 定义state类型
interface State {
  token: string | null,
  userInfo: any | null
}

// 定义injection key
export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    token: localStorage.getItem('token') || null,
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null')
  },
  mutations: {
    setToken(state: State, token: string) {
      state.token = token
      localStorage.setItem('token', token)
    },
    clearToken(state: State) {
      state.token = null
      localStorage.removeItem('token')
    },
    setUserInfo(state: State, systemUserInfo: object) {
      const userInfoStr = JSON.stringify(systemUserInfo)
      localStorage.setItem('userInfo', userInfoStr)
    }
  },
  getters: {
    isAuthenticated: (state: State) => !!state.token
  }
})

// 定义自己的useStore组合式函数
export function useStore() {
  return baseUseStore(key)
}
